package com.wonders.demo.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;

/**
 * @Auther: song
 * @Data： 2018/7/3010
 * @Description
 *
 *      http请求工具类
 */
public class HttpUtils {

    /**
     * 发送get请求
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static JSONObject syncGet(String url) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = (new Request.Builder()).url(url).build();
        Response response = okHttpClient.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }

    /**
     * 发送post请求
     * @param url 请求地址
     * @param params 请求参数
     * @return
     * @throws Exception
     */
    public static Object syncPost(String url, Map<String, Object> params, String tgt) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        RequestBody requestBody = null;
        Iterator var5 = params.keySet().iterator();
        while(var5.hasNext()) {
            String key = (String)var5.next();
            builder.add(key,params.get(key)+"");
        }

        requestBody = builder.build();
        Request request = null;
        if(StringUtils.isEmpty(tgt)){
            request =  (new Request.Builder()).url(url).post(requestBody).build();
        }else {
            request =(new Request.Builder()).url(url).post(requestBody).header("tgt", tgt).build();
        }
        Response response = okHttpClient.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }

    /**
     * 发送post请求
     * @param url 请求地址
     * @param params 请求参数
     * @return 绕过证书校验
     * @throws Exception
     */
    public static Object syncPost2(String url, Map<String, Object> params, String tgt) throws Exception {

        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory())
                .hostnameVerifier(DO_NOT_VERIFY).build();
//        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        RequestBody requestBody = null;
        Iterator var5 = params.keySet().iterator();
        while(var5.hasNext()) {
            String key = (String)var5.next();
            builder.add(key,params.get(key)+"");
        }

        requestBody = builder.build();
        Request request = null;
        if(StringUtils.isEmpty(tgt)){
            request =  (new Request.Builder()).url(url).post(requestBody).build();
        }else {
            request =(new Request.Builder()).url(url).post(requestBody).header("tgt", tgt).build();
        }
        Response response = okHttpClient.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }

    /**
     * 同步post请求
     * 返回json对象
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static Object syncPostWithType(String url, String json) throws Exception {
        OkHttpClient     okHttpClient = new OkHttpClient();

        RequestBody      requestBody  = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
        Request          request      = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response         response     = okHttpClient.newCall(request).execute();

        return JSONObject.parse(response.body().string());
    }
}
